package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.gulimall.common.constant.WareConstant;
import com.atguigu.gulimall.ware.entity.WmsPurchaseDetailEntity;
import com.atguigu.gulimall.ware.service.WmsPurchaseDetailService;
import com.atguigu.gulimall.ware.service.WmsWareSkuService;
import com.atguigu.gulimall.ware.vo.MergeVo;
import com.atguigu.gulimall.ware.vo.PurchaseFinishVo;
import com.atguigu.gulimall.ware.vo.PurchaseItemFinishVo;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.gulimall.common.utils.PageUtils;
import com.atguigu.gulimall.common.utils.Query;

import com.atguigu.gulimall.ware.dao.WmsPurchaseDao;
import com.atguigu.gulimall.ware.entity.WmsPurchaseEntity;
import com.atguigu.gulimall.ware.service.WmsPurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;


@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseDao, WmsPurchaseEntity> implements WmsPurchaseService {

    @Resource
    private WmsPurchaseDetailService wmsPurchaseDetailService;

    @Resource
    private WmsWareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {

        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>().eq("status", 0).or().eq("status", 1)
        );

        return new PageUtils(page);
    }

    /**
     * 合并采购单明细
     * @param mergeVo
     */
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //TODO 确认采购单状态是0，1（新建，已分配）才可以合并

        Long purchaseId = mergeVo.getPurchaseId();
        if (null == purchaseId){
            //自动生成一条新的采购单
            WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
            wmsPurchaseEntity.setCreateTime(new Date());
            wmsPurchaseEntity.setUpdateTime(new Date());
            //采购单设置状态初始值：新建
            wmsPurchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATE.getCode());
            this.save(wmsPurchaseEntity);
            purchaseId = wmsPurchaseEntity.getId();
        }
        //将采购申请明细合并到指定的采购单
        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;
        List<WmsPurchaseDetailEntity> collect = items.stream().map((i) -> {
            WmsPurchaseDetailEntity wmsPurchaseDetailEntity = new WmsPurchaseDetailEntity();
            wmsPurchaseDetailEntity.setId(i);
            wmsPurchaseDetailEntity.setPurchaseId(finalPurchaseId);
            //合并采购单明细，将状态从新建改为已分配
            wmsPurchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
            return wmsPurchaseDetailEntity;
        }).collect(Collectors.toList());
        wmsPurchaseDetailService.updateBatchById(collect);

        //修改采购单，更新信息
        WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
        wmsPurchaseEntity.setUpdateTime(new Date());
        wmsPurchaseEntity.setId(purchaseId);
        this.updateById(wmsPurchaseEntity);
    }

    @Override
    public void received(List<Long> ids) {
        //1.领取条件：确认当前采购单是新建或者分配状态
        List<WmsPurchaseEntity> collect = ids.stream().map(id -> {
            return this.getById(id);
        }).filter(purchase -> {
            return purchase.getStatus() == WareConstant.PurchaseStatusEnum.CREATE.getCode() || purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //2.改变采购单状态
        this.updateBatchById(collect);
        //3.改变采购单明细状态， 从过滤后的采购单中查找对应的采购单明细
        collect.forEach( item -> {
            //3.1采购单对应的采购单明细
            List<WmsPurchaseDetailEntity> purchaseDetailByPurchaseId = wmsPurchaseDetailService.queryListPurchaseDetailByPurchaseId(item.getId());
            //3.2包装采购单明细数据
            List<WmsPurchaseDetailEntity> purchaseDetailEntities = purchaseDetailByPurchaseId.stream().map(entity -> {
                WmsPurchaseDetailEntity wmsPurchaseDetailEntity = new WmsPurchaseDetailEntity();
                //根据id更改状态为采购中
                wmsPurchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                wmsPurchaseDetailEntity.setId(entity.getId());
                return wmsPurchaseDetailEntity;
            }).collect(Collectors.toList());
            //3.2更新采购单数据
            wmsPurchaseDetailService.updateBatchById(purchaseDetailEntities);
        });

    }

    @Transactional
    @Override
    public void finish(PurchaseFinishVo purchaseFinishVo) {

        Long id = purchaseFinishVo.getId();
        //2.改变采购单明细的状态
        List<PurchaseItemFinishVo> items = purchaseFinishVo.getItems();
        ArrayList<WmsPurchaseDetailEntity> updates = new ArrayList<>();
        boolean flag = true;
        for (PurchaseItemFinishVo itemFinishVo : items) {
            WmsPurchaseDetailEntity purchaseDetailEntity = new WmsPurchaseDetailEntity();
            if (itemFinishVo.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode());
            }else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                //3.将成功采购的进行入库
                WmsPurchaseDetailEntity purchaseDetailEntityById = wmsPurchaseDetailService.getById(itemFinishVo.getItemId());
                wareSkuService.addStock(purchaseDetailEntityById.getSkuId(), purchaseDetailEntityById.getWareId(), purchaseDetailEntityById.getSkuNum());
            }
            purchaseDetailEntity.setId(itemFinishVo.getItemId());
            purchaseDetailEntity.setReason(itemFinishVo.getReason());
            updates.add(purchaseDetailEntity);
        }
        wmsPurchaseDetailService.updateBatchById(updates);
        //1.改变采购单状态
        WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
        wmsPurchaseEntity.setId(purchaseFinishVo.getId());
        wmsPurchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode(): WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        wmsPurchaseEntity.setUpdateTime(new Date());
        this.updateById(wmsPurchaseEntity);



    }

}